<template>
  <div class="row col">
    <div class="col">
      <q-scroll-area class="fit" @scroll="handleScroll">
        <q-list bordered class="q-ma-md" :clickable="false">
          <q-item v-ripple v-for="(item, index) in forumlist" :key="index">
            <q-item-section>
              <div style="display: flex">
                <q-avatar size="40px">
                  <q-img style="width: 40px; height: 40px" :src="imagePath(item.avatar)"></q-img>
                </q-avatar>
                <q-item-label style="font-size: 15px">{{ item.unnamed }}</q-item-label>
              </div>
              {{ item.forumText }}
              <viewer class="label-list q-mb-sm" style="max-height: 100px" ref="viewer" :options="options" :images="item.viedoUrls" v-if="item.viedoUrls && item.viedoUrls.length > 0" @inited="inited">
                <img v-for="(src, index) in item.viedoUrls" class="q-pl-sm" :key="index" :src="src" style="object-fit: contain; max-height: 100%; max-width: 150px" />
              </viewer>
              <!-- 评论区域 -->
              <!-- <div class="bg-grey-5 q-ma-md" style="min-height: 100px"></div> -->
              <div v-if="item.topic && item.topic != null">
                <q-chip dense icon="bookmark" v-if="item.topic.label != null">{{ item.topic.label }}</q-chip>
              </div>
              <q-list class="">
                <q-item style="display: flex" :clickable="true">
                  <q-item-section style="display: flex; flex-direction: row" @click="showForum(index)"><q-icon name="mdi-chat-processing-outline" size="xs" style="text-align: center"></q-icon> <span v-if="Array.isArray(item.childForums)">{{ item.childForums.length }}</span> <span v-else>0</span></q-item-section>
                </q-item>
                <div style="position: absolute; right: 100px; top: 70%">
                  <q-icon name="mdi-thumb-up-outline" :color="likeColor(item.id)" size="xs" style="text-align: center" @click="addLike(item.id, $event)">点赞</q-icon>
                </div>
                <q-item v-show="item.showForumFlag" :clickable="true">
                  <q-item-section style="">
                    <Forum :parentId="item.id"></Forum>
                  </q-item-section>
                </q-item>
                <!--              子评论               -->
                <q-item v-show="item.showForumFlag">
                  <q-item-section>
                    <q-list bordered class="q-ma-md" :clickable="false">
                      <q-item v-ripple v-for="(childItem, index2) in item.childForums" :key="index2">
                        <q-item-section>
                          <div style="display: flex">
                            <q-avatar size="40px">
                              <q-img style="width: 40px; height: 40px" :src="imagePath(childItem.avatar)"></q-img>
                            </q-avatar>
                            <q-item-label style="font-size: 15px">{{ childItem.unnamed }}</q-item-label>
                          </div>
                          {{ childItem.forumText }}
                          <viewer class="label-list q-mb-sm" style="max-height: 100px" ref="viewer" :options="options" :images="childItem.viedoUrls" v-if="childItem.viedoUrls && childItem.viedoUrls.length > 0" @inited="inited">
                            <img v-for="(src, index) in childItem.viedoUrls" class="q-pl-sm" :key="index" :src="src" style="object-fit: contain; max-height: 100%; max-width: 150px" />
                          </viewer>
                          <div style="display: flex; justify-content: center" @click="showChildChildForum(index, index2, childItem.showChildForumFlag)">
                            <!-- <q-item-section style="display: flex; flex-direction: row"> -->
                            <q-icon name="mdi-chat-processing-outline" size="xs" style="text-align: center"></q-icon>回复
                            <!-- </q-item-section> -->
                          </div>
                          <!-- 放置所有子评论的子评论 -->
                          <div class="bg-grey-1">
                            <div class="bg-grey-2" v-if="childItem.showChildForumFlag">
                              <Forum :parentId="childItem.id" :discussion="'@' + childItem.unnamed + ' ' + childItem.forumText"></Forum>
                            </div>
                            <div v-if="childItem.childForums && childItem.childForums.length > 0">
                              <q-list bordered class="q-ma-md" :clickable="false">
                                <q-item v-ripple v-for="(item3, index3) in childItem.childForums" :key="index3" :clickable="false">
                                  <q-item-section>
                                    <div style="display: flex">
                                      <q-avatar size="40px">
                                        <q-img style="width: 40px; height: 40px" :src="imagePath(childItem.avatar)"></q-img>
                                      </q-avatar>
                                      <q-item-label style="font-size: 15px">{{ childItem.unnamed }}</q-item-label>
                                    </div>

                                    {{ item3.forumText }}
                                    <viewer class="label-list q-mb-sm" style="max-height: 100px" ref="viewer" :options="options" :images="item3.viedoUrls" v-if="item3.viedoUrls && item3.viedoUrls.length > 0" @inited="inited">
                                      <img v-for="(src, index) in item3.viedoUrls" class="q-pl-sm" :key="index" :src="src" style="object-fit: contain; max-height: 100%; max-width: 150px" />
                                    </viewer>
                                    <q-item-label class="bg-grey-2 q-pa-sm">{{ item3.discussion }}</q-item-label>
                                    <div style="display: flex; justify-content: center" @click="showLastForum(index, index2, index3)">
                                      <!-- <q-item-section style="display: flex; flex-direction: row"> -->
                                      <q-icon name="mdi-chat-processing-outline" size="xs" style="text-align: center"></q-icon>回复
                                      <!-- </q-item-section> -->
                                    </div>
                                    <div class="bg-grey-2" v-if="item3.showChildForumFlag">
                                      <Forum :parentId="childItem.id" :discussion="'@' + item3.unnamed + ' ' + item3.forumText"></Forum>
                                    </div>
                                  </q-item-section>
                                </q-item>
                              </q-list>
                            </div>
                          </div>
                        </q-item-section>
                      </q-item>
                    </q-list>
                  </q-item-section>
                </q-item>
              </q-list>
            </q-item-section>
          </q-item>
        </q-list>
      </q-scroll-area>
    </div>
  </div>
</template>

<script>
import Viewer from 'viewerjs';
import 'viewerjs/dist/viewer.css';
import Forum from './forum.vue';

export default {
  name: 'TopicList',
  components: {
    Forum,
  },
  props: {
    topicsString: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      options: {
        title: false,
      },
      ws: null,
      emptyTopicForm: {
        topic: {},
        unnamedFlag: false,
        forumText: '',
        viedoUrls: [],
      },
      imgUrl: `${process.env.BASE_URL}/sys/common/static`,
      page: 1, // 当前页码
      limit: 5, // 每页加载的数据数量
      isLoading: false, // 加载状态
      hasMore: true, // 是否还有更多数据
      index: 0, // 当前图片的索引
      // 话题列表数据
      forumlist: [],
      headers: [{ name: 'Authorization', value: localStorage.Authorization }],
      viewer: null,
      url: {
        list: '/forum/list',
        getUserLike: '/forum/getUserLike',
      },
      userLikeForumIds: [],
    };
  },
  watch: {
    topicsString(newValue, oldValue) {
      this.getForumList();
    },
    immediate: false, // 实现初始化时监听
  },
  computed: {},
  methods: {
    addLike(forumId, event) {
      if (event.target.classList.contains('text-cyan-2')) {
        event.target.classList.remove('text-cyan-2');
      } else {
        event.target.classList.add('text-cyan-2');
      }
      this.$axios.post('/user/forumLike/add', { userId: this.$store.state.User.info.username, forumId });
    },
    imagePath(src) {
      let path = '';
      if (src) {
        if (src.startsWith('http')) {
          return src;
        }
        path = `${this.imgUrl}/${src}`;
      }
      return path;
    },
    showLastForum(index, index2, index3) {
      this.forumlist[index].childForums[index2].childForums[index3].showChildForumFlag = !this.forumlist[index].childForums[index2].childForums[index3].showChildForumFlag;
    },
    showChildChildForum(index, childIndex, mesg) {
      this.forumlist[index].childForums[childIndex].showChildForumFlag = !this.forumlist[index].childForums[childIndex].showChildForumFlag;
      // this.$set(this.forumlist[index].childForums[childIndex], 'showChildForumFlag', false);
    },
    showForum(index) {
      this.forumlist[index].showForumFlag = !this.forumlist[index].showForumFlag;
      // if (this.forumlist[index].showForumFlag === true) {
      //   // 没有的话添加一个子空话题
      //   if (this.forumlist[index].childForums === undefined) {
      //     this.forumlist[index].childForums = [];
      //   }
      //   this.forumlist[index].childForums.push(this.emptyTopicForm);
      // }
      // if (this.forumlist[index].showForumFlag === false) {
      //   // 没有提交则删除新加的
      //   this.forumlist[index].childForums.pop();
      // }
    },
    loadData() {
      if (!this.hasMore || this.isLoading) return;
      this.isLoading = true;
      // 模拟异步请求数据
      let newItems = [];
      this.$axios
        .get(this.url.list, { params: { key: this.topicsString, pageNo: this.page, pageSize: this.limit } })
        .then((res) => {
          // 处理新数据，为每个元素添加 showForumFlag 属性
          res.result.records.map((v, i) => {
            this.$set(v, 'showForumFlag', false);
          });
          newItems = res.result.records;

          // 处理新数据中的子论坛，为每个子论坛元素添加 showChildForumFlag 属性
          newItems.map((v, i) => {
            if (v.childForums) {
              v.childForums.map((v1) => {
                this.$set(v1, 'showChildForumFlag', false);
                v1.childForums.map((v2) => {
                  this.$set(v2, 'showChildForumFlag', false);
                });
              });
            }
          });

          // 将新数据添加到旧数据后面
          this.forumlist = this.forumlist.concat(newItems);

          // 如果加载的数据数量小于每页数量，说明没有更多数据了
          if (newItems.length < this.limit) {
            this.hasMore = false;
          }
          this.page++;
          this.isLoading = false;
        })
        .catch((error) => {
          console.error('数据加载出错:', error);
          this.isLoading = false;
        });
    },
    getForumList() {
      let newItems = [];
      this.page = 1;
      this.$axios.get(this.url.list, { params: { key: this.topicsString, pageNo: this.page, pageSize: this.limit } }).then((res) => {
        res.result.records.map((v, i) => {
          // v.showForumFlag = false;
          this.$set(v, 'showForumFlag', false);
        });
        newItems = res.result.records;
        this.forumlist = res.result.records;
        this.forumlist.map((v, i) => {
          if (v.childForums) {
            v.childForums.map((v1) => {
              // v1.showChildForumFlag = true;
              this.$set(v1, 'showChildForumFlag', false);
              v1.childForums.map((v2) => {
                this.$set(v2, 'showChildForumFlag', false);
              });
            });
          }
        });
      });
      // this.page = 1;
      this.hasMore = true;
      this.isLoading = false;
      this.page++;
    },
    handleScroll(event) {
      const { verticalPosition, verticalContainerSize, verticalSize } = event;
      // 当滚动到底部时加载更多数据
      if (verticalPosition + verticalContainerSize >= verticalSize - 100 && this.hasMore) {
        // this.page++;
        this.loadData();
      }
    },
    // 初始化预览组件
    inited(viewer) {
      this.$viewer = viewer;
    },
    uploadFile() {
      this.$refs.dialog.show();
    },
    wsInit() {
      this.ws.onopen = () => {
        this.ws.send('服务已连接');
      };
      this.ws.onclose = () => {
        console.log('服务器关闭');
      };
      this.ws.onmessage = (message) => {
        console.log('收到服务器消息');
        const forum = JSON.parse(message.data);
        if (forum.parentId == null) {
          forum.showForumFlag = false;
          this.forumlist.push(forum);
        } else {
          this.forumlist.map((v, i) => {
            if (v.childForums) {
              if (v.id === forum.parentId) {
                forum.showChildForumFlag = false;
                v.childForums.push(forum);

                return;
              }
              if (!v.childForums) {
                return;
              }
              v.childForums.map((v1) => {
                // v1.showChildForumFlag = true;
                if (v1.id === forum.parentId) {
                  forum.showChildForumFlag = false;
                  v1.childForums.push(forum);

                  return;
                }
                if (!v1.childForums) {
                  return;
                }
                // this.$set(v1, 'showChildForumFlag', false);
                v1.childForums.map((v2) => {
                  if (v2.id === forum.parentId) {
                    forum.showChildForumFlag = false;
                    v2.childForums.push(forum);
                  }
                  // this.$set(v2, 'showChildForumFlag', false);
                });
              });
            }
          });
        }
      };
      this.ws.onerror = (error) => {
        console.log('报错了');
        console.log(error);
      };
    },
    sendMessage() {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        // 发送消息
        this.ws.send(this.message);
      } else {
        console.error('WebSocket 连接未打开，无法发送消息');
      }
    },
    getUserLike() {
      this.$axios.get(this.url.getUserLike).then((res) => {
        this.userLikeForumIds = res.result;
        console.log(this.userLikeForumIds);
      });
    },
    likeColor(id) {
      const flag = this.userLikeForumIds.includes(id);
      console.log(flag);
      if (flag) {
        return 'cyan-2';
      }
      return 'black-4';
    },
  },
  created() {
    // 连接WebSocket服务端，然后初始化监听事件
    this.ws = new WebSocket(`ws://localhost:9008/weather-api/websocket/forum/${this.$store.state.User.info.id}`);
    this.wsInit();
  },
  mounted() {
    // console.log(this.topicsString);
    // this.avatar = this.imagePath(this.$store.state.User.info.avatar);
    // this.$set(this.topicsString);
    this.page = 1;
    this.forumlist = [];
    this.loadData();
    this.getUserLike();
  },
};
</script>
<style lang="stylus"
       scope></style>
